package com.android.qjpmc.widget.manager;

import com.android.qjpmc.R;
import com.android.qjpmc.widget.bean.ProfileFileBean;
import com.android.qjpmc.widget.interfaces.UploadListener;
import com.android.qjpmc.widget.manager.retrofit.RetrofitJsonManager;
import com.android.qjpmc.widget.retrofithelper.http.Url;
import com.android.qjpmc.widget.retrofithelper.rxschedulers.RxSchedulersHelper;
import com.android.qjpmc.widget.retrofithelper.rxsubscriber.ProgressObserver;
import com.android.qjpmc.widget.utils.FileUtils;
import com.android.qjpmc.widget.utils.ToastUtils;
import com.android.qjpmc.widget.utils.UIUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * @Author zhangshuqi
 * @CreateTime 2018/4/12
 * @Describe
 */

public class UploadFileManager {
    private List<String> fileBeanStringList;
    private List<ProfileFileBean> fileBeanList;
    private UploadListener mUploadListener;
    private int mIndex;
    private boolean isShowLoading;

    private UploadFileManager() {

    }


    private static class UploadFileManagerSingleton {
        private static final UploadFileManager INSTANCE = new UploadFileManager();

    }

    public static UploadFileManager getInstance() {
        return UploadFileManager.UploadFileManagerSingleton.INSTANCE;
    }


    public void uploadPath(List<String> imageList, String modelName, UploadListener listener) {
        init(listener);
        uploadFileToServer(mIndex, imageList, modelName);
    }


    public void uploadPath(String imagePath, String modelName, UploadListener listener) {
        init(listener);
        List<String> list = new ArrayList<>();
        list.add(imagePath);
        uploadFileToServer(mIndex, list, modelName);
    }

    public void uploadFileBean(ProfileFileBean bean, UploadListener listener) {
        init(listener);

        List<ProfileFileBean> list = new ArrayList<>();
        list.add(bean);
        uploadFileBeanToServer(mIndex, list);
    }

    public void uploadFileBean(List<ProfileFileBean> list, UploadListener listener) {
        init(listener);
        uploadFileBeanToServer(mIndex, list);
    }

    private void init(UploadListener listener) {
        mIndex = 0;
        mUploadListener = listener;
        fileBeanList = new ArrayList<>();
        fileBeanStringList = new ArrayList<>();
        isShowLoading = false;
    }

    private void uploadFileToServer(int index, final List<String> files, final String modelName) {
        if (files == null || files.size() == 0) return;
        if (index > files.size()) return;
        final String path = files.get(index);
        if (path.startsWith(Url.BASE_URL)) {
            return;
        }
        showLoadingDialog();
        Luban.with(UIUtils.getContext())
                .load(path)
                .setCompressListener(new OnCompressListener() { //设置回调
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onSuccess(File file) {
                        startUploadFilePath(file, files, modelName);
                    }

                    @Override
                    public void onError(Throwable e) {
                        startUploadFilePath(new File(path), files, modelName);
                    }
                }).launch();    //启动压缩
    }

    private void showLoadingDialog() {
        if (!isShowLoading) {
            LoadingFragmentManager.getInstance().showLoadingDialog(null, UIUtils.getString(R.string.Uploading_Photos));
            isShowLoading = true;
        }

    }

    private void startUploadFilePath(final File file, final List<String> files, final String modelName) {
        MultipartBody multipartBody = filesToMultipartBody(file, "file");
        RetrofitJsonManager.getInstance().getApiService().uploadFileWithRequestBody(  multipartBody).compose(RxJavaHttpManager.applyTransformer())
                .subscribe(new ProgressObserver<String>(false, null) {

                    @Override
                    public void _onError(String errorMessage, int errorCode) {
                        ToastUtils.showShort(errorMessage);
                        LoadingFragmentManager.getInstance().dismissLoadingDialog();
                        mUploadListener.onUploadFailed();
                    }

                    @Override
                    public void _onNext(String uploadFileBean) {
                       /* String json = JSON.toJSONString(uploadFileBean);
                        UploadImageBean uploadImageBean = JSONObject.parseObject(json, UploadImageBean.class);
                        if (uploadImageBean.success) {
                            String data = (String) uploadImageBean.data;

                        } else {
                            _onError(uploadImageBean.message, Integer.parseInt(uploadImageBean.errCode));
                        }*/
                        fileBeanStringList.add( uploadFileBean);
                        if (fileBeanStringList.size() == files.size()) {
                            // 成功
                            mUploadListener.onUploadStringSuccess(fileBeanStringList);
                            mIndex = 0;
                            isShowLoading = false;
                            LoadingFragmentManager.getInstance().dismissLoadingDialog();
                        } else {
                            mIndex++;
                            uploadFileToServer(mIndex, files, modelName);
                        }
                    }

                });

    }

    private void uploadFileBeanToServer(int index, final List<ProfileFileBean> files) {
        if (files == null || files.size() == 0) return;
        if (index > files.size()) return;
        final ProfileFileBean profileFileBean = files.get(index);
        if (profileFileBean.filePath.startsWith(Url.BASE_URL)) {
            if (files.size() == 1) {
                mUploadListener.onUploadSuccess(files);
            } else {
                fileBeanList.add(profileFileBean);
                mIndex++;
                uploadFileBeanToServer(mIndex, files);
            }
            return;
        }
        showLoadingDialog();
        Luban.with(UIUtils.getContext())
                .load(profileFileBean.filePath)
                .setCompressListener(new OnCompressListener() { //设置回调
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onSuccess(File file) {

                        startUploadFileBean(file, profileFileBean, files);
                    }

                    @Override
                    public void onError(Throwable e) {
                        startUploadFileBean(new File(profileFileBean.filePath), profileFileBean, files);
                    }
                }).launch();    //启动压缩


    }

    private void startUploadFileBean(final File file, final ProfileFileBean profileFileBean, final List<ProfileFileBean> files) {

        MultipartBody stringRequestBodyMap = filesToMultipartBody(file, "file");
        RetrofitJsonManager.getInstance().getApiService().uploadFileWithRequestBody(" ").compose(RxSchedulersHelper.applyIoTransformer()).subscribe(new ProgressObserver<ResponseBody>(false, null) {
            @Override
            public void _onError(String errorMessage, int errorCode) {
                ToastUtils.showShort(errorMessage);
                mUploadListener.onUploadFailed();
                LoadingFragmentManager.getInstance().dismissLoadingDialog();

            }

            @Override
            public void _onNext(ResponseBody responseBody) {
                profileFileBean.file = file;
                try {
                    profileFileBean.fileId = responseBody.string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                fileBeanList.add(profileFileBean);

                if (fileBeanList.size() == files.size()) {
                    // 成功
                    mUploadListener.onUploadSuccess(fileBeanList);
                    mIndex = 0;
                    isShowLoading = false;
                    LoadingFragmentManager.getInstance().dismissLoadingDialog();
                } else {
                    mIndex++;
                    uploadFileBeanToServer(mIndex, files);
                }
            }
        });

    }

    public MultipartBody filesToMultipartBody(File file) {

        MultipartBody.Builder builder = new MultipartBody.Builder();
        RequestBody requestBody = RequestBody.create(FileUtils.guessMimeType(file.getName()), file);
        builder.addFormDataPart("avatar", file.getAbsolutePath(), requestBody);
        builder.setType(MultipartBody.FORM);

        return builder.build();
    }

    public MultipartBody filesToMultipartBody(File file, String name) {

        MultipartBody.Builder builder = new MultipartBody.Builder();
        RequestBody requestBody = RequestBody.create(FileUtils.guessMimeType(file.getName()), file);
        // RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"),file);
        builder.addFormDataPart(name, file.getName(), requestBody);
        builder.setType(MultipartBody.FORM);
        return builder.build();
    }


 }
